﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MisClient
{
    public partial class FrmConfirmMoney3 : BaseForm
    {
        private IBLL.ICustomer cusBLL = MisCLL.DAOFactory.CreateInstance().GetRemoteCustomer();
        private IBLL.ICusDep cusDepBLL = MisCLL.DAOFactory.CreateInstance().GetRemoteCusDep();
        private IBLL.ISacf sacfBLL = MisCLL.DAOFactory.CreateInstance().GetRemoteSacf();

        private decimal hj = 0;

        public FrmConfirmMoney3()
        {
            InitializeComponent();
        }

        private void FrmConfirmMoney3_Load(object sender, EventArgs e)
        {
            DateTime dt = DateTime.Now;
            this.openStarDate.Value = dt.Date.AddDays(-200);
            this.chkF.Text = "Y";
            this.txtOperUser.Text = accountUser.UserCode;
            this.txtDate.Text = DateTime.Now.ToShortDateString();
        }

        private void btnQuit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            DateTime dt = DateTime.Now;
            this.openEndDate.Value = dt;
            this.openStarDate.Value = dt.Date.AddDays(-200);
            this.txtCusCode.Clear();
            this.txtCus.Clear();
            this.txtInvoiceNum.Clear();
            this.txtCusDepCode.Clear();
            this.txtCusDep.Clear();
            this.chkF.Clear();

            this.dataGridView1.Rows.Clear();
            this.dataGridView2.Rows.Clear();
            this.chkF.Text = "Y";

            this.openEndDate.Enabled = true;
            this.openStarDate.Enabled = true;
            this.txtCusCode.Enabled = true;
            this.txtInvoiceNum.Enabled = true;
            this.txtCusDepCode.Enabled = true;
            this.chkF.Enabled = true;

            this.btnAdd.Enabled = false;
            this.btnPrint.Enabled = false;
            this.btnQuit.Enabled = false;
            this.btnCan.Enabled = true;

            this.openStarDate.Focus();
        }

        private void openStarDate_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.openEndDate.Focus();
            }
        }

        private void openEndDate_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.txtCusCode.Focus();
            }
        }

        private void txtCusCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (!string.IsNullOrEmpty(this.txtCusCode.Text.Trim()))
                {
                    MisModel.Customer customer = cusBLL.GetById(this.txtCusCode.Text.Trim());
                    if (customer == null)
                    {
                        MessageBox.Show("无此代码或不属于本部分！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.txtCusCode.Focus();
                        return;
                    }
                    else
                    {
                        this.txtCus.Text = customer.Customer_;
                        MisModel.CusDep cusDep = cusDepBLL.GetById(this.txtCusCode.Text.Trim());
                        if (cusDep != null)
                        {
                            this.txtCusDepCode.Text = cusDep.CusDep_;
                            this.txtCusDep.Text = cusDep.Depart;
                        }
                    }
                }
                this.txtInvoiceNum.Focus();
            }
        }

        private void txtInvoiceNum_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (string.IsNullOrEmpty(this.txtInvoiceNum.Text.Trim()))
                {
                    MessageBox.Show("不能为空！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.txtInvoiceNum.Focus();
                    return;
                }
                else
                    this.txtCusDepCode.Focus();
            }
        }

        private void txtCusDepCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.chkF.Focus();
            }
        }

        private void chkF_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (!string.IsNullOrEmpty(this.txtCusCode.Text.Trim()))
                {
                    MisModel.Customer customer = cusBLL.GetById(this.txtCusCode.Text.Trim());
                    if (customer == null)
                    {
                        MessageBox.Show("无此代码或不属于本部分！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        this.txtCusCode.Focus();
                        return;
                    }
                }
                if (string.IsNullOrEmpty(this.txtInvoiceNum.Text.Trim()))
                {
                    MessageBox.Show("不能为空！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.txtInvoiceNum.Focus();
                    return;
                }
                if (string.IsNullOrEmpty(this.chkF.Text.Trim()))
                {
                    MessageBox.Show("不能为空！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.chkF.Focus();
                    return;
                }
                else if (!this.chkF.Text.Trim().ToUpper().Equals("Y") && !this.chkF.Text.Trim().ToUpper().Equals("N"))
                {
                    MessageBox.Show("应置为：Y(是)或N(否)！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.chkF.Focus();
                    return;
                }
                if (searchSacf())
                {
                    this.openEndDate.Enabled = false;
                    this.openStarDate.Enabled = false;
                    this.txtCusCode.Enabled = false;
                    this.txtInvoiceNum.Enabled = false;
                    this.txtCusDepCode.Enabled = false;
                    this.chkF.Enabled = false;
                    this.chkF.Enabled = false;

                    this.btnSave.Enabled = true;
                }
            }
        }

        private Boolean searchSacf()
        {
            Dictionary<string, object> dictionary = new Dictionary<string, object>();
            StringBuilder sb = new StringBuilder();
            sb.Append(" and m.date>=@startDate and m.date<=@endDate");
            dictionary.Add("@startDate", this.openStarDate.Value.ToShortDateString());
            DateTime time = DateTime.Parse(this.openEndDate.Value.ToShortDateString());
            time = time.Date.AddDays(1);
            dictionary.Add("@endDate", time.ToShortDateString());
            sb.Append(" and m.no_cus=@noCus");
            dictionary.Add("@noCus", this.txtInvoiceNum.Text.Trim());
            if (!string.IsNullOrEmpty(this.txtCusCode.Text.Trim()))
            {
                sb.Append(" and m.cus_id=@cusId");
                dictionary.Add("@cusId", this.txtCusCode.Text.Trim());
            }
            if (!string.IsNullOrEmpty(this.txtCusDepCode.Text.Trim()))
            {
                sb.Append(" and m.cus_dep=@cusDep");
                dictionary.Add("@cusDep", this.txtCusDepCode.Text.Trim());
            }

            DataTable dt = sacfBLL.GetArticleNoAll(sb.ToString(), dictionary);
            hj = 0;
            if (dt != null && dt.Rows.Count > 0)
            {
                String txtZw = this.chkF.Text.Trim();
                if (!txtZw.ToUpper().Equals("Y"))
                    txtZw = "N";

                decimal wse = 0;
                decimal hse = 0;
                decimal sl = 0;
                decimal hsje = 0;
                decimal wsje = 0;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string no = dt.Rows[i][0].ToString();
                    string sm1 = string.Format("{0}-{1}-{2}", dt.Rows[i][2].ToString(), dt.Rows[i][3].ToString(), dt.Rows[i][4].ToString());
                    string sm2 = string.Format("库:{0} 未税额:{1} 含税额:{2} 件数:{3} 税率:{4}", dt.Rows[i][1].ToString(), dt.Rows[i][5].ToString(), dt.Rows[i][6].ToString(), dt.Rows[i][7].ToString(), dt.Rows[i][8].ToString());
                    int rowCount = this.dataGridView1.RowCount;
                    String[] DataRow = new String[8];
                    DataRow[0] = (rowCount + 1).ToString();
                    DataRow[1] = no;
                    DataRow[2] = txtZw;
                    DataRow[3] = string.Format("{0:f}", dt.Rows[i][9].ToString());
                    DataRow[4] = sm1;
                    DataRow[5] = sm2;
                    DataRow[6] = string.Format("{0}", dt.Rows[i][6].ToString());
                    DataRow[7] = string.Format("{0}", dt.Rows[i][5].ToString());

                    if (!string.IsNullOrEmpty(DataRow[7]))
                    {
                        wsje += decimal.Parse(DataRow[7]);
                    }
                    if (!string.IsNullOrEmpty(DataRow[6]))
                    {
                        hsje += decimal.Parse(DataRow[6]);
                    }

                    this.dataGridView1.Rows.Add(DataRow);
                    hj += (decimal)dt.Rows[i][6];

                    rowCount = this.dataGridView2.RowCount;
                    String[] goodDataRow = new String[11];
                    DataTable dt1 = sacfBLL.GetArticleGoodsAll(no);
                    if (dt1 != null && dt1.Rows.Count > 0)
                    {
                        for (int j = 0; j < dt1.Rows.Count; j++)
                        {
                            goodDataRow[0] = (rowCount + 1).ToString();
                            goodDataRow[1] = dt1.Rows[j]["no"].ToString();
                            goodDataRow[2] = dt1.Rows[j]["nono"].ToString();
                            goodDataRow[3] = dt1.Rows[j]["id"].ToString();
                            goodDataRow[4] = dt1.Rows[j]["goods"].ToString();
                            goodDataRow[5] = dt1.Rows[j]["unit"].ToString();
                            goodDataRow[6] = dt1.Rows[j]["sl"].ToString();
                            goodDataRow[7] = dt1.Rows[j]["price_fs"].ToString();
                            goodDataRow[8] = dt1.Rows[j]["je_fs"].ToString();
                            goodDataRow[9] = dt1.Rows[j]["tax"].ToString();
                            goodDataRow[10] = dt1.Rows[j]["NO_JS"].ToString();

                            if (!string.IsNullOrEmpty(dt1.Rows[j]["sl"].ToString()))
                            {
                                sl += decimal.Parse(dt1.Rows[j]["sl"].ToString());
                            }

                            if (!string.IsNullOrEmpty(dt1.Rows[j]["price_fs"].ToString()))
                            {
                                wse += decimal.Parse(dt1.Rows[j]["price_fs"].ToString());
                            }
                            if (!string.IsNullOrEmpty(dt1.Rows[j]["je_fs"].ToString()))
                            {
                                hse += decimal.Parse(dt1.Rows[j]["je_fs"].ToString());
                            }
                            this.dataGridView2.Rows.Add(goodDataRow);
                        }
                    }
                }
                label8.Text = string.Format("●合计 数量：{0} 未税价：{1} 未税额：{2}", sl, wse, hse);
                label6.Text = string.Format("●合计 含税金额：{0} 未税金额：{1}", hsje, wsje);
                return true;
            }
            else
            {
                MessageBox.Show("查无符合条件的记录！", "信息窗", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            return false;
        }

        private void btnCan_Click(object sender, EventArgs e)
        {
            this.openStarDate.Enabled = false;
            this.openEndDate.Enabled = false;
            this.txtCusCode.Enabled = false;
            this.txtInvoiceNum.Enabled = false;
            this.txtCusDepCode.Enabled = false;
            this.chkF.Enabled = false;

            this.btnSave.Enabled = false;
            this.btnCan.Enabled = false;
            this.btnAdd.Enabled = true;
            this.btnPrint.Enabled = true;
            this.btnQuit.Enabled = true;
        }

        private void btnRef_Click(object sender, EventArgs e)
        {
            Point mousePoint = MousePosition;
            Point point = this.PointToClient(mousePoint);
            this.contextMenuStrip1.Show(this, point);
        }

        private void toolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("calc.exe");
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("请检查各项目是否正确，是否保存[Y/N]？", "提问窗", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                return;
            string f7 = "0";
            if (this.dataGridView2.Rows.Count > 0)
            {
                IList<MisEntity.Sacf> list = new List<MisEntity.Sacf>();
                MisEntity.Sacf entity = null;
                DataGridViewRow dr = null;
                for (int i = 0; i < this.dataGridView2.Rows.Count; i++)
                {
                    dr = this.dataGridView2.Rows[i];
                    entity = new MisEntity.Sacf();
                    entity.NO = dr.Cells["data1"].Value.ToString();
                    entity.NONO = decimal.Parse(dr.Cells["data2"].Value.ToString());
                    entity.ID = dr.Cells["data3"].Value.ToString();
                    entity.OPER = accountUser.UserCode;
                    entity.F7 = char.Parse(f7);
                    entity.NO_JS = dr.Cells["noJs"].Value.ToString();
                    list.Add(entity);
                }
                sacfBLL.Article(list);
                this.btnSave.Enabled = false;
                this.btnCan.Enabled = false;
                MessageBox.Show(string.Format("单据已存盘，总金额：{0}。是否打印清单[y/n]？", hj), "提问窗", MessageBoxButtons.OK, MessageBoxIcon.Question);

                this.btnAdd.Enabled = true;
                this.btnPrint.Enabled = true;
                this.btnQuit.Enabled = true;
            } 
        }
    }
}
